<!-- eslint-disable no-console -->
<!--------------------------------
 - @Author: Ronnie Zhang
 - @LastEditor: Ronnie Zhang
 - @LastEditTime: 2023/12/05 21:29:56
 - @Email: zclzone@outlook.com
 - Copyright © 2023 Ronnie Zhang(大脸怪) | https://isme.top
 --------------------------------->

<template>
  <CommonPage>
    <MeCrud ref="$table" v-model:query-items="queryItems" :scroll-x="1200" :columns="columns" :get-data="api.read">
      <MeQueryItem label="订单号" :label-width="50">
        <n-input v-model:value="queryItems.orderNum" type="text" placeholder="请输入订单号" clearable />
      </MeQueryItem>
      <MeQueryItem label="客户名称">
        <n-input v-model:value="queryItems.userName" type="text" placeholder="顾客姓名" clearable />
      </MeQueryItem>
      <MeQueryItem label="配送状态">
        <n-select v-model:value="queryItems.deliveryStatus" :options="deliveryStatusOptions" />
      </MeQueryItem>
      <MeQueryItem label="订单日期" :content-width="300">
        <n-date-picker
          v-model:formatted-value="queryItems.orderDateRange" value-format="yyyy-MM-dd" type="daterange"
          clearable
        />
      </MeQueryItem>
    </MeCrud>
  </CommonPage>
  <!-- 新增和修改model -->
  <MeModal ref="$modalOrderRefund">
    <n-form
      ref="formOrderRefundRef" :model="orderRefundCurrent" label-placement="left" :label-width="100" :style="{
        maxWidth: '440px',
      }"
    >
      <n-form-item label-align="right" label="订单号" path="orderNum">
        <n-input v-model:value="orderRefundCurrent.orderNum" placeholder="请输入标签名称" />
      </n-form-item>
      <n-form-item label-align="right" label="退款金额" path="refundMoney">
        <n-input-number v-model:value="orderRefundCurrent.refundMoney" placeholder="请输入退款金额">
          <template #prefix>
            $
          </template>
        </n-input-number>
      </n-form-item>
      <n-form-item label-align="right" label="退款原因" path="refundReason">
        <n-input v-model:value="orderRefundCurrent.refundReason" placeholder="请输入退款原因" />
      </n-form-item>
    </n-form>
  </MeModal>
  <!-- 选择配送方式model -->
  <MeModal ref="$modalDeliverType" title="配送信息" width="420px">
    <n-form
      ref="formOrderRefundRef" :model="orderRefundCurrent" label-placement="left" :label-width="100" :style="{
        maxWidth: '440px',
      }"
    >
      <n-form-item label-align="right" label="收件人" path="userName">
        <n-input v-model:value="currentDeliveryOrder.userName" disabled />
      </n-form-item>
      <n-form-item label-align="right" label="手机号" path="userPhone">
        <n-input v-model:value="currentDeliveryOrder.userPhone" disabled />
      </n-form-item>
      <n-form-item label-align="right" label="地址" path="deliveryAddress">
        <n-input v-model:value="currentDeliveryOrder.deliveryAddress" type="textarea" rows="2" disabled>
          <template #suffix>
            100米
          </template>
        </n-input>
      </n-form-item>
      <n-form-item label-align="right" label="同城快递" path="currentErrandType">
        <n-radio-group v-model:value="currentDeliveryOrder.currentErrandType" name="currentErrandType" @update:value="onUpdateDeliveryType">
          <n-space>
            <n-radio value="1" name="basic-demo">
              自配
            </n-radio>
            <n-radio value="2" name="basic-demo">
              达达快递
            </n-radio>
            <n-radio value="3" name="basic-demo">
              达达快递
            </n-radio>
            <n-radio value="4" name="basic-demo">
              达达快递
            </n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
    </n-form>
  </MeModal>
</template>

<script setup>
import apiGlobal from '@/api'
import { MeCrud, MeModal, MeQueryItem } from '@/components'
import { useModal } from '@/composables'
import { NButton } from 'naive-ui'
import api from './api'

defineOptions({ name: 'GoodsMgt' })
const [$modalOrderRefund] = useModal()
const [$modalDeliverType] = useModal()
const formOrderRefundRef = ref(null)
const router = useRouter()
const route = useRoute()
const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({
  needDeliveryOrder: true,
})
const deliveryStatusOptions = ref([])

const columns = [
  { title: '销售单号', key: 'orderNum', width: 100 },
  {
    title: '订单类型',
    width: 100,
    render: (rew) => {
      if (rew.deliveryType === 1) { // 销售订单
        return '堂食订单'
      }
      return '外卖订单'
    },
  },
  {
    title: '客户名称',
    width: 90,
    render: (rew) => {
      return h(
        NButton,
        { onClick: () => toDeliveryOrder(rew.orderNum) },
        { default: () => rew.deliveryOrder?.userName ? rew.deliveryOrder.userName : rew.userName },
      )
    },
  },
  {
    title: '订单状态',
    key: 'orderStatusName',
    width: 80,
  },
  {
    title: '支付状态',
    key: 'payStatusName',
    width: 80,
  },
  {
    title: '订单原价',
    key: 'originalMoney',
    width: 100,
  },
  {
    title: '优惠价格',
    key: 'originalMoney',
    width: 100,
    render: (items) => {
      return items.discountMoney + items.mlMoney
    },
  },
  {
    title: '应收价格',
    key: 'receivableMoney',
    width: 100,

  },
  { title: '运费', key: 'deliveryMoney', width: 90 },
  { title: '订单日期', key: 'orderDate', width: 100 },
  { title: '创建日期', key: 'createTime', width: 100 },
  {
    title: '操作',
    key: 'actions',
    width: 250,
    align: 'center',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      const arr = [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => openOrderDetailsModel(row),
          },
          {
            default: () => '详情',
            icon: () => h('i', { class: 'i-carbon:user-role text-14' }),
          },
        ),
      ]
      // 订单状态:0:待接单,1:制配中,2:待取货,3:在路上,4:已完成
      if (row.orderStatus === 0) { // 待接单
        arr.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => confirmOrder(row),
          },
          {
            default: () => '接单',
            icon: () => h('i', { class: 'i-carbon:user-role text-14' }),
          },
        ))
      }
      if (row.orderStatus === 1) { // 制配中
        arr.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => makingCompleted(row),
          },
          {
            default: () => '制配完成',
            icon: () => h('i', { class: 'i-carbon:user-role text-14' }),
          },
        ))
      }
      if (row.orderStatus === 2) { // 制配中
        if (row.deliveryType === 1) {
          arr.push(h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              secondary: true,
              onClick: () => takeFood(row),
            },
            {
              default: () => '取餐',
              icon: () => h('i', { class: 'i-carbon:user-role text-14' }),
            },
          ))
        }
        else {
          arr.push(h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              secondary: true,
              onClick: () => takeFood(row),
            },
            {
              default: () => '外卖取货',
              icon: () => h('i', { class: 'i-carbon:user-role text-14' }),
            },
          ))
        }
      }
      if (row.orderStatus === 3) { // 制配中
        arr.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => finishOrder(row),
          },
          {
            default: () => '订单完成',
            icon: () => h('i', { class: 'i-carbon:user-role text-14' }),
          },
        ))
      }
      if (row.deliveryType === 2 && row.deliveryOrder.deliveryStatus === 0) {
        arr.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => modalDeliverTypeSelect(row),
          },
          {
            default: () => '选择配送',
            icon: () => h('i', { class: 'i-carbon:user-role text-14' }),
          },
        ))
      }
      // 选择跑腿平台
      return arr
    },
  },
]
onMounted(async () => {
  if (route.query.orderNum) {
    queryItems.value.orderNum = route.query.orderNum
  }
  $table.value?.handleSearch()
  deliveryStatusOptions.value = await apiGlobal.getEnumOptions('DeliveryStatusEnum')
})
function openOrderDetailsModel(row) {
  router.push({ path: `/order/sale-order-details/${row.id}`, query: { orderNum: row.orderNum, orderId: row.id } })
}
//
function toDeliveryOrder(orderNum) {
  router.push({ path: `/order/delivery-order`, query: { orderNum } })
}
const orderRefundCurrent = ref({})
/**
 * 配送方式选择
 */
const currentDeliveryOrder = ref({})
async function modalDeliverTypeSelect(row) {
  currentDeliveryOrder.value = row.deliveryOrder
  $modalDeliverType.value?.open({
    width: '500px',
    okText: '确定',
    cancelText: '取消',
    async onOk() {
      if (!currentDeliveryOrder.value.currentErrandType) {
        $message.error('请选择配送方式')
        return false
      }
      //
      await api.confirmDeliveryOrder(currentDeliveryOrder.value)
      $table.value?.handleSearch()
    },
    onCancel(message) {
      $message.info(message ?? '已取消')
    },
  })
}
async function confirmOrder(row) {
  api.confirmByOrderId(row.id)
  $table.value?.handleSearch()
}
async function makingCompleted(row) {
  api.makingCompleted(row.id)
  $table.value?.handleSearch()
}
async function takeFood(row) {
  api.takeFood(row.id)
  $table.value?.handleSearch()
}
async function finishOrder(row) {
  api.finishOrder(row.id)
  $table.value?.handleSearch()
}
function onUpdateDeliveryType(value) {
  if (value === 1) {
    currentDeliveryOrder.value.userPhone = ''
    currentDeliveryOrder.value.deliveryAddress = ''
  }
}
</script>

<style scoped>
/** */
:deep(.n-input__suffix) {
  align-items: end;
}
</style>
